<?php


namespace App\Http\Controllers\Es;
use App\Http\Controllers\Controller;
use Elasticsearch\ClientBuilder;
use App\Http\Controllers\ResultJsonController;

class EsController extends Controller
{

    private static $instance;

    private static $clicent;
    public $host = [];

    public static function getInstance($host='')
    {
        if(!(self::$instance instanceof self))
        {
            self::$instance = new self($host);
        }
        return self::$instance;
    }

    /**
     * 私有的_construct,防止被new
     */
    private function __construct($host)
    {
        if(!empty($host))
        {
            $this->host = $host;
        }
        if(empty($this->host))
        {
            $this->host = config('es.coordinate');
        }
        if(empty($this->host))
        {
           app('resultJson')->setMessage("请配置host")->errorJson();
        }
        self::$clicent = ClientBuilder::create()->setHosts($this->host)->build();
    }

    /**
     * 防止clone
     */
    private function __clone()
    {
        // TODO: Implement __clone() method.
    }

    /**
     * 防止被反序列化
     */
    private function __wakeup()
    {
        // TODO: Implement __wakeup() method.
    }

    /**
     * 获取集群状态
     */
    public function getClusterStatus()
    {
        return self::$clicent->cluster()->stats();
    }

    /**
     * 提供有关群集中碎片分配的说明
     */

    public function getAllocationExplain()
    {
        return self::$clicent->cluster()->allocationExplain();
    }

    /**
     * 获取集群内存情况
     */
    public function getAllocationMemory()
    {
        // TODO: Implement
    }
    /**
     * 创建一个mapping
     */
    public function createMapping($params)
    {
        return self::$clicent->indices()->putMapping($params);   //create 创建一个索引和mapping
    }

    /**
     * 获取一个mapping
     */
    public function getMapping($params)
    {
        return self::$clicent->indices()->getMapping($params);
    }
    /**
     * 批量添加数据到ES
     */
    public function bulkData($params)
    {
        return self::$clicent->bulk($params);
    }
    /**
     * 通过id获取一条数据
     */
    public function getSingleById($params)
    {
        return self::$clicent->get($params);
    }
    /**
     * 通过id单条更新数据
     */
    public function updateById($params)
    {
        return self::$clicent->update($params);
    }
    /**
     * 查询数据
     */
    public function queryData($params)
    {
        return self::$clicent->search($params);
    }
}